﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
using Oracle.ManagedDataAccess.Client;
using System.Data.SQLite;
using System.IO;
using System.Text.RegularExpressions;

namespace NoORM.Core.DbAcceess
{
    /// <summary>
    /// 数据库连接构建者
    /// </summary>
    public class ConnectionBuilder
    {
        public const string SqlConnection = "System.Data.SqlClient.SqlConnection";
        public const string MySqlConnection = "MySql.Data.MySqlClient.MySqlConnection";
        public const string OracleConnection = "Oracle.ManagedDataAccess.Client.OracleConfiguration";
        public const string SqliteConnection = "System.Data.SQLite.SQLiteConnection";

        /// <summary>
        /// 构建数据库连接对象
        /// </summary>
        /// <param name="config">连接字符串配置</param>
        /// <returns></returns>
        public IDbConnection Builder(ConnectionStringConfig config)
        {
            IDbConnection connection = null;
            switch (config.ConnectionClassName)
            {
                case SqlConnection:
                    connection = new SqlConnection(config.ConnectionString);
                    break;
                case MySqlConnection:
                    connection = new MySqlConnection(config.ConnectionString);
                    break;
                case OracleConnection:
                    connection = new OracleConnection(config.ConnectionString);
                    break;
                case SqliteConnection:
                    Regex reg = new Regex(@"(?<=Data\s+Source\s*=\s*).+?(?=;)");
                    string fileName = reg.Match(config.ConnectionString).Value;
                    if (fileName.IndexOf("\\") < 0)
                    {
                        string currentPath = Path.Combine(Directory.GetCurrentDirectory());
                        string dbPath = Path.Combine(currentPath, fileName);
                        string connectionString = reg.Replace(config.ConnectionString, dbPath);
                        connection = new SQLiteConnection(connectionString);
                    }
                    else
                    {
                        connection = new SQLiteConnection(config.ConnectionString);
                    }
                    break;
                default:
                    connection = new SqlConnection(config.ConnectionString);
                    break;
            }
            return connection;
        }
    }
}
